﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Web;
using System.Web.Mvc;
using FileUploadDemoForMVC.Models;

namespace FileUploadDemoForMVC.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 简单的文件上传，不支持大文件上传，一般默认是4m文件。如果需要上传大文件，那么就需要修改配置文件中的httpRuntime节点的属性。具体设置请参考配置文件
        /// </summary>
        /// <param name="file">上传文件（在视图中文件类型的name要和后台接收文件的参数一致）</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {

            var fileName = file.FileName;
            var filePath = Server.MapPath($"~/{fileName}");
            file.SaveAs(filePath);
            ViewBag.msg = "上传成功";
            return View();
        }

        /// <summary>
        /// 带有文件校验的上传
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadFile(BlogModel model)
        {
            if (ModelState.IsValid)
            {
                var fileName = model.BlogPhoto.FileName;
                var filePath = Server.MapPath($"~/{fileName}");
                model.BlogPhoto.SaveAs(filePath);
                ModelState.Clear();
                ViewBag.msg2 = "上传成功";
            }
            else
            {
                ViewBag.msg2 = "验证失败";
            }
            
            return View("Index");
        }
    }
}